package othello;

import java.util.Scanner;

public class Othello {

	public static void main(String[] args) {
		if (args.length != 3) {
			System.out.println("arguments: [c/w/b, see below] [search time in seconds] [search depth]");
			System.out.println("\t\tc=CPU VS CPU, w=you play as white, b=you play as black");
			System.exit(0);
		}

		int searchTime = Integer.valueOf(args[1]);
		int searchDepth = Integer.valueOf(args[2]);
		char gameChoice = args[0].charAt(0);

		boolean blackCPU = true;
		boolean whiteCPU = true;

		// Set CPU control to true or false
		switch (gameChoice) {
		case 'c':
			break;
		case 'w':
			blackCPU = true;
			whiteCPU = false;
			break;
		case 'b':
			blackCPU = false;
			whiteCPU = true;
			break;
		default:
			System.out.println("Invalid input parameters");
			System.exit(0);
			break;
		}

		// Initial board setup
		int[][] board = new int[8][8];
		board[4][3] = 1; // Black
		board[3][4] = 1;
		board[3][3] = 2; // White
		board[4][4] = 2;
		State currentState = new State(board);

		String diskPos = "";
		Scanner in = new Scanner(System.in);
		MiniMax ai = new MiniMax(searchDepth, (long) searchTime * 1000);
		Action suggestion;

		while (true) {
			try {
				// Use the AI suggestion or let user input move
				if (blackCPU && currentState.getPlayer() == 1) {
					suggestion = ai.miniMax(currentState);
					currentState.makeMove(suggestion);
					currentState.printState();
				} else {
					suggestion = ai.miniMax(currentState);
					currentState.printState(suggestion);
					System.out.println("Black 1, White 2, Suggestion X");
					System.out.println("It is Black's turn, please enter move (e.g. a1):  ");
					
					boolean isLegal=false;
					do {
						diskPos = in.next();
						isLegal = ai.isLegalMove(diskPos);
						if (isLegal){
							currentState.makeMove(diskPos);
						} else{
							System.out.println("Illegal move, please try again:");
						}
			        } while (!isLegal);
					
				}
				if (whiteCPU && currentState.getPlayer() == 2) {
					suggestion = ai.miniMax(currentState);
					currentState.makeMove(suggestion);
					currentState.printState();
				} else {
					suggestion = ai.miniMax(currentState);
					currentState.printState(suggestion);
					System.out.println("Black 1, White 2, Suggestion X");
					System.out.println("It is White's turn, please enter move (e.g. a1): ");
					
					boolean isLegal=false;
					do {
						diskPos = in.next();
						isLegal = ai.isLegalMove(diskPos);
						if (isLegal){
							currentState.makeMove(diskPos);
						} else{
							System.out.println("Illegal move, please try again:");
						}
			        } while (!isLegal);
					
				}
				if (diskPos.equals("x")) {
					in.close();
					break;
				}
			} catch (Exception e) {
				System.out.println("Game finished...");
				break;
			}
		}
	}
}
